function is_email(strEmail) 
{
    if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
	return true;
    else
	return false;
}

function is_name(name)
{
    if (name.search(/^[a-zA-Z]{1,32}$/) != -1) {
	return true;
    }
    else {
	return false;
    }
}

function is_date(strDate)
{
    if (strDate.search(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/) != -1) {
	return true;
    }
    else {
	return false;
    }
}

function is_login()
{
    //check user login
    var username = $(".user-nickname").text();
    if (username == "" || username == "undefined") {
        //window.location.href="/user/login/";
	return false;
    }
    return true;
}


function is_numberic(strNumber)
{
    if (strNumber.search(/^[0-9\.]{1,20}$/) != -1) {
	return true;	
    }
    else {
	return false;
    }
}


//age_list_ctrl
function post_age_list_ctrl()
{
    $("#post_age_list").show();
    return false;
}

function post_age_list_elemt()
{
    $("#post_age_name").val($(this).text());
    $("#post_age_id").val($(this).attr("id"));
    $("#post_age_list").hide();
}

//body_list_ctrl
function post_body_list_ctrl()
{
    $("#post_body_list").show();
    return false;
}

function post_body_list_elemt()
{
    $("#post_body_name").val($(this).text());
    $("#post_body_id").val($(this).attr("id"));
    $("#post_body_list").hide();
}

//area_list_ctrl
function post_area_list_ctrl()
{
    $("#post_area_list").show();
    return false;
}

function post_area_list_elemt()
{
    $("#post_area_name").val($(this).text());
    $("#post_area").val($(this).attr("id"));
    $("#post_area_list").hide();
}
function post_select_box_init()
{
    $("#post_age_list_ctrl").click(post_age_list_ctrl);
    $("#post_age_name").click(post_age_list_ctrl);
    $("#post_age_block").mouseleave(function(){$("#post_age_list").hide();});
    $("#post_age_list").find("li").each(function(){$(this).click(post_age_list_elemt);});

    $("#post_body_list_ctrl").click(post_body_list_ctrl);
    $("#post_body_name").click(post_body_list_ctrl);
    $("#post_body_block").mouseleave(function(){$("#post_body_list").hide();});
    $("#post_body_list").find("li").each(function(){$(this).click(post_body_list_elemt);});
    
    $("#post_area_list_ctrl").click(post_area_list_ctrl);
    $("#post_area_name").click(post_area_list_ctrl);
    $("#post_area_block").mouseleave(function(){$("#post_area_list").hide();});
    $("#post_area_list").find("li").each(function(){$(this).click(post_area_list_elemt)});
}

function checkbox_click()
{
    var cl = $(this).attr("class");
    if (cl == "check-box check-true") {
	$(this).attr("class", "check-box check-false");
    }
    else {
	$(this).attr("class", "check-box check-true");
    }
}

function select_gen_goal_click()
{
    var gen_name = $(this).text();
    var id = $(this).attr("id");
    if (id != "goal_name_tab" && id != "add_this_goal_shadow") {
	$("#post_goal_name").text(gen_name);
	$("#gen_goal_id").text(id);
    }
    if (id == "add_this_goal_shadow") {
	var ggid = $("#gen_goal_id").text();	
	if (ggid == 0) {
	    $("#post_goal_name").text(gen_name);
	    $("#goal_name").val(gen_name);
	}
    }
    
    //check user login
 //   var username = $(".user-nickname").text();
 //   if (username == "" || username == "undefined") {
 //       window.location.href="/user/joinorlogin/ggid/"+id;
 //       return false;
 //   }
    $(this).unbind("click");
    $(this).fancybox({
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
	});
    //$("#goal_name").val("");
    $(this).click();
}


function cheer_callback(response)
{
}

//post goal
/**
function goal_submit()
{
    var gen_goal_id = $("#gen_goal_id").text();
    var goal_name    = $("#goal_name").val();
    var age_id      = $("#post_age_id").val();
    var body_id     = $("#post_body_id").val();
    var area_id     = $("#post_area").val();
    var purpose     = $("#purpose").val();
    var deadline    = $("#deadline").val();
    var content     = $("#content").val();

    if (purpose == "e.g.class reunion,wedding,prenatal/post-natal fitness etc.") {
	alert("ready for..is empty.");
	return false;
    }
    if (is_date(deadline) == false) {
	alert("deadline is not valid. it should like (mm/dd/yyyy)");
	return false;
    }
    if (purpose.length ==0 ) {
	alert("purpose is empty.");
	return false;
    }
    if (purpose.length > 50) {
	alert("Your 'to get ready for' is too long.(max 50 characters in length)");
	return false;
    }

    var data = {
	gen_goal_id : gen_goal_id,
	goal_name   : goal_name,
	age_id      : age_id,
	body_id     : body_id,
	area_id     : area_id,
	purpose     : purpose,
	deadline    : deadline,
	content     : content
    };

    $.ajax({
	'type' : 'POST',
	'data' : data,
	'dataType' : 'json',
	'url'  : '/goal/post',
	success : function(msg){
	    if (msg.status == 0) {
		//alert("Goal posted successfully");
		$(".show_pop3").click();
	    }
	    else if (msg.status == 1) {
		//user not login
		//location.href="/user/login";
		$("#pop_login_ctrl").click();
	    }
	    else {
		alert(msg.content);
	    }

	},
	error : function(xhr) {
	    alert("Exception");
	}
    
    });
    return true;
}
*/

function goal_submit()
{
    var goal_name   = $("#submit_goal_name").val();
    var budget    = $("#s2_budget").val();
    var content     = $("#content").val();
    alert(budget);
    if (is_numberic(budget) == false) {
        alert("Budget should be a number.");
        return false;
    }
    if (content.length > 2000) {
        alert("Your goal detail is too long.(max 2000 characters in length)");
        return false;
    }
    var data = {
        goal_name : goal_name,
        budget    : budget,
        content   : content
    };

    $.ajax({
	'type' : 'POST',
	'data' : data,
	'dataType' : 'json',
	'url'  : '/goal/post',
	success : function(msg){
	    if (msg.status == 0) {
		//alert("Goal posted successfully");
            $("#s2_budget").val("");
            $("#content").val("");
            $(".show_pop3").click();
	    }
	    else if (msg.status == 1) {
		//user not login
		//location.href="/user/login";
		$("#pop_login_ctrl").click();
	    }
	    else {
		alert(msg.content);
	    }

	},
	error : function(xhr) {
	    alert("Exception");
	}
    
    });
    return true;
}

var g_gid = 0;
function trainerhire_submit()
{
    var trainer_types = get_gen_goals("trainer_type_list");
    var trainer_gender = 0;
    $("#gender_list").find("label").each(function(){{if ($(this).attr("class") == "check-box check-true"){trainer_gender=$(this).attr("id")}}});
    var contact_phone = $("#contact_phone").val();
    if (trainer_types == "") {
        alert("Please select trainers you might be interested in");
        return false;
    }
    var data = {
	trainer_types : trainer_types,
	trainer_gender : trainer_gender,
	contact_phone : contact_phone
    };
    
    $.ajax({
	'type' : 'POST',
	'data' : data,
	'dataType' : 'json',
	'url'  : '/goal/hiretrainer',
	success : function(msg){
	    if (msg.status == 0) {
		alert("Congratulations! Your goal is posted");
		$.fancybox.close();
		var goal_name = $("#post_goal_name").text();
		if ($("#fb_conntected").attr("class") == "check-box check-true") {
		    var content = 'I just posted my next fitness goal on fitwow.com: my goal is"'+goal_name+'"';
		    var msg1 = {
		    message : content,
		    name : "goal detail",
		    link : "http://fitwow.com/goal/detail/gid/"+msg.data.gid
		    };
		    fb_publish_feed("me", msg1, cheer_callback);
		}
		$("#email_invite").attr("gid", msg.data.gid);
		$(".share-f").attr("gid", msg.data.gid);
		$(".share-f").attr("goal_name", goal_name);
		var html="Goal: "+goal_name+"<i><a href='/goal/detail/gid/"+msg.data.gid+"'>View goal detail</a></i>";
		$("#pop5 h1").html(html);
		$("#show_pop5_ctrl").click();
		g_gid = msg.data.gid;
		//location.href="/goal/community/gid/"+msg.data.gid;
	    }
	    else {
		alert(msg.content);
	    }

	},
	error : function(xhr) {
	    alert("Exception");
	}
    
    });
    return true;
}



function cheer_submit()
{
    var gid = $("#gid").val();
    var cheer_content = $("#cheer_content").val();
    
    //TODO:facebook status
    if (gid ==0) {
        alert("Please select the goal.");
        return false;
    }
    if (cheer_content == "") {
        alert("Content is empty");
        return false;
    }
    if (cheer_content.length > 1000) {
        alert("Cheer content can not be more than 1000 characters. (you have "+cheer_content.length+")");
        return false;
    }
    var data = {
        gid :gid,
        cheer_content : cheer_content
    };
    $.ajax({
	'type' : 'POST',
	'data' : data,
	'dataType' : 'json',
	'url'  : '/goal/cheer',
	success : function(msg){
	    if (msg.status == 0) {
        
		alert("Cheer post success");
		$.fancybox.close();
		//post to facebook post
		if ($("#post_to_facebook").attr("class") == "check-box check-true") {
		    var content = "I just became my friend's cheerleader on fitwow";
		    var msg = {
			message : content,
			name : "You have become a cheerleader for your friends",
			link : "http://fitwow.com/goal/detail/gid/"+gid
		    };
		    fb_publish_feed("me", msg, cheer_callback);
		}
	    }
	    else {
		alert(msg.content);
	    }
        $("#cheer_content").val("");
	},
	error : function(xhr) {
	    alert("Exception");
	}
    
    });
    return true;
}

function like_submit()
{
    if (is_login() == false) {
        $("#pop_login_ctrl").click();
        return false;
    }
    var obj = $(this).parent().parent();
    var cheer_id = $(this).attr("cheer_id"); 
    var bid = $(this).attr("bid");
    var data = {
	cheer_id : cheer_id,
	bid      : bid
    };
    $.ajax({
	'type' : 'POST',
	'data' : data,
	'dataType' : 'json',
	'url'  : '/goal/like',
	success : function(msg){
	    if (msg.status == 0) {
		var html = $(obj).html();
		html = html.replace(/\d+ likes/g, msg.data + ' likes');
		$(obj).html(html);
		$(obj).find(".like").each(function(){$(this).click(like_submit)});
	    }
	    else {
		alert(msg.content);
	    }

	},
	error : function(xhr) {
	    alert("Exception");
	}
    
    });
}

function submit_search()
{
    var keyword = $("#keyword").val();
    if (keyword == "Search goals") {
	return false;
    }
    if (keyword.length > 0) {
	if (typeof(cur_url) != "undefined")
	    location.href = cur_url + "keyword/" + keyword;
	else 
	    location.href = "/goal/search/keyword/" + keyword;
	return false;
    }
    return false;
}


//email invite
function email_invite()
{
    var email0 = $("#email0").val();
    var email1 = $("#email1").val();
    var email2 = $("#email2").val();
    var email3 = $("#email3").val();
    var email4 = $("#email4").val();
    var flag = 0;
    if (email0 == "" && email1 == "" && email2 == "" && email3 == "" && email4 == "") {
	alert("Email is empty.");
	return false;
    }
    if ((email0 != "" && !is_email(email0)) || (email1 != "" && !is_email(email1)) || (email2 != "" && !is_email(email2))
	|| (email3 != "" && !is_email(email3)) || (email4 != "" && !is_email(email4))) {
	alert("Email is not valid.");
	return false;
    }

    var data = {
	email0 : email0,
	email1 : email1,
	email2 : email2,
	email3 : email3,
	email4 : email4,
	gid : $(this).attr("gid")
    };
    $.ajax({
	'type' : 'POST',
	'data' : data,
	'dataType' : 'json',
	'url'  : '/goal/emailinvite',
	success : function(msg){
	    if (msg.status == 0) {
		alert("Invite success.");
		$.fancybox.close();
	    }
	    else {
		alert(msg.content);
	    }
	},
	error : function(xhr) {
	    alert("Exception");
	}
    });
    return false;
}

//fb goal share
function fb_goal_share()
{
    var goal_name = $(this).attr("goal_name");
    var content = "My next fitness goal is "+goal_name+", come cheer me up;";
    var link    = "http://fitwow.com/goal/detail/gid/"+$(this).attr("gid");
    var msg = {
	message : content,
	name : "Cheer me up",
	link : link
    };
    fb_publish_feed("me", msg, cheer_callback);
    alert("Shared successfully.");
    $.fancybox.close();
}

//goal name submit 2012-04-15
function gn_submit()
{
    var goal_name = $(this).siblings().val();
    $(this).siblings().val("");
    if (goal_name == "") {
        alert("subject is empty, please enter.");
        return false;
    }
    if (goal_name.length > 50) {
        alert("subject is too long, the max length is 50.");
        return false;
    }
    $("#submit_goal_name").val(goal_name);
    $("#post_goal_name").text(goal_name);
    if (is_login() == false) {
        //send request to the server and pop the join windows
        var data = {goal_name:goal_name};
        $.ajax({
            'type' : 'POST',
            'data' : data,
            'dataType' : 'json',
            'url'  : '/goal/gnsubmit',
            success : function(msg){
                $("#pop_login_ctrl").click();
            },
            error : function(xhr) {
                alert("Exception");
            }
        });
    }
    else {
        
        $(".show_pop2").click();
    }
}


$(function(){

    $("#keyword").click(function(){
	if ($(this).val() == "Search goals")
	    $(this).val("");
    });
    $("#keyword").blur(function(){
	if ($(this).val() == "")
	    $(this).val("Search goals")
    });
    $("#deadline").click(function(){
	if ($(this).val() == "mm/dd/yyyy")
	    $(this).val("");
    });
    $("#deadline").blur(function(){
	if ($(this).val() == "")
	    $(this).val("mm/dd/yyyy");
    });

    $("#search_goal").click(submit_search);
    $("#keyword").bind('keyup', function(event){
	if (event.keyCode == 13) {
	    $("#search_goal").click();
	}	
    });

    $(".show_option_1").click(function(){
	$(this).removeClass("now").siblings().removeClass("now")
	$(this).addClass("now")

	var id_1 = $(this).attr("tab");
	var id_2 = $(this).siblings().attr("tab");
	$("#" + id_1).show();
	$("#" + id_2).hide();

	id_1 = $(this).attr("tab2");
	if (id_1 != undefined) {
	    id_2 = $(this).siblings().attr("tab2");
	    $("#" + id_1).show();
	    $("#" + id_2).hide();
	}
    });
    $(".show_option_2").click(function(){
	$(this).removeClass("now").siblings().removeClass("now")
	$(this).addClass("now")
	var id_1 = $(this).attr("tab");
	var id_2 = $(this).siblings().attr("tab");
	$("#" + id_1).show();
	$("#" + id_2).hide();

	id_1 = $(this).attr("tab2");
	if (id_1 != undefined) {
	    id_2 = $(this).siblings().attr("tab2");
	    $("#" + id_1).show();
	    $("#" + id_2).hide();
	}
    });
    
    
    $(".check-box").click(checkbox_click);
    
    
    $(".show_goal_text").click(function(){
			$(this).hide();
            $(this).siblings().show();
            var obj = $(this).siblings("input");
            
			$(this).siblings("input").css({"height":"30px","marginTop":"5px","lineHeight":"26px"});
			$(this).siblings(".sub").click(function(){
                
			    var goal_name = $(obj).val();
                if (goal_name.length > 50) {
                    alert("The goal name is too long.");
                    return;
                }                   
			    if (goal_name.length > 0) {
				$("#goal_name").val(goal_name);
				$("#gen_goal_id").text("0");
				$("#post_goal_name").text(goal_name);
				$("#goal_name_tab").click();
			    }
			});
    });
    
    //pop window
    $('.show_pop1').fancybox({
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
	});
	$('.show_pop2').click(select_gen_goal_click);
    
	$('.show_pop3').fancybox({
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
	});
    
    $('.show_pop4').fancybox({
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
        'onStart'           : function(){if (is_login() == false){return false;}}
    }).click(function(){
            if (is_login() == false) {
                $("#pop_login_ctrl").click();
                return false;
            }
            $("#gid").val($(this).attr("id"));
            var goal_name = $(this).attr("goal_name");
            goal_name = "Goal: " + goal_name;
            goal_name += "<i><a href='/goal/detail/gid/"+$(this).attr("id")+"'>View goal detail</a></i>";
            $("#h1_goal_name").html(goal_name);
            $("#pop4_goal_detail").attr('href', '/goal/detail/gid/'+$(this).attr("id"));
    });
    
    //join pop
    $('.show_join').fancybox({
	    'width'				: '75%',
	    'height'			: '75%',
	    'autoScale'			: false,
	    'transitionIn'		: 'none',
	    'transitionOut'		: 'none'
    });
    //login pop
    $('.show_login').fancybox({
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
    });	
    $('.show_pop5').fancybox({
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'onClosed' : function(){if (g_gid > 0){var gid = g_gid; g_gid = 0;location.href="/goal/community/gid/"+gid;}}
	});
    $('.show_pop6').fancybox({
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
	});

    $("#purpose").click(function(){
	    if ($(this).val() == "e.g.class reunion,wedding,prenatal/post-natal fitness etc.")
		$(this).val("");
    });
    $("#purpose").blur(function(){
	    if ($(this).val() == "")
		$(this).val("e.g.class reunion,wedding,prenatal/post-natal fitness etc.");
    });
    //goal post
    $("#goal_submit").click(goal_submit);
    $("#trainerhire_submit").click(trainerhire_submit);
    $("#hiretrainer_close").click(function(){$.fancybox.close();}); 

    $("#gender_list").find("label").each(function(){$(this).click(function(){
	    if ($(this).attr("class") == "check-box check-true") {
		$(this).parent().siblings().find("label").each(function(){$(this).attr("class", "check-box check-false")});
	    }
	    else {
		$(this).parent().siblings().find("label").each(function(){$(this).attr("class", "check-box check-true")});
		
	    }
    })});
    
    //cheer me on
    $("#cheer_submit").click(cheer_submit);
    $(".like").click(like_submit);
    
    
    //email_invite
    $("#email_invite").click(email_invite);
    $("#join_sign_in_ctrl").fancybox({
	'width'			: '75%',
	'height'		: '75%',
	'autoScale'		: false,
	'transitionIn'		: 'none',
	'transitionOut'		: 'none'
    });
    $(".share-f").click(fb_goal_share);
    //post select box init
    post_select_box_init();
    //trainer bid check login
    $("#trainer_bid_button").click(function(){
	if (is_login() == false) {
	    $("#pop_login_ctrl").click();
	    return false;
	}    
    });
    
    //goal_name submit button added by liyangguang 2012-04-15
    $(".gn_submit").click(gn_submit);
});
